package com.server;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

public class RegisteDevice extends HttpServlet {
	/**
	 * 注册设备
	 * 接收userId，psw，imei
	 * 更新数据库students
	 * 返回:
	 * status:
	 * -1  <----> 请求错误
	 *  1  <----> 操作成功
	 *
	 */

	private String userId;		//账号
	private String psw;			//密码
	private String imei;		//设备串号
	private int status;			//记录返回状态
	private final static int REQUSET_ERROR = -1;
	private final static int OPERATE_SUCCESS = 1;
	private final static int DEVICE_EXISTED = 2;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		userId = request.getParameter("id");
		psw = request.getParameter("psw");
		imei = request.getParameter("imei");

		if(userId != null && !userId.equals("") && psw != null && !psw.equals("") && imei != null && !imei.equals("")){
			String sql = "SELECT password FROM students WHERE sno = " + userId + " LIMIT 1";
			DBTools db = new DBTools();
			ResultSet rs = db.query(sql);
			try {
				//账号存在？
				if(rs.next()){
					//密码正确？
					if(psw.equals(rs.getString("password"))){
						sql = "SELECT sno FROM students WHERE IMEI = " + imei + " LIMIT 1";
						db = new DBTools();
						rs = db.query(sql);
						//设备是否已存在？
						if (rs.next()) {
							System.out.println("DEVICE_EXISTED");
							status = DEVICE_EXISTED;
						}else{
							sql = "UPDATE students SET IMEI = '"+imei+"' WHERE sno = '"+userId+"'";
							db = new DBTools();
							int i = db.update(sql);
							//数据库更新成功？
							if (i == 1) {
								System.out.println("OPERATE_SUCCESS");
								status = OPERATE_SUCCESS;
							}
						}
					}
				}
			} catch (SQLException e) {
				System.out.println(sql);
				e.printStackTrace();
			}

		}else {
			status = REQUSET_ERROR;
		}

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.write("" + status);
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
